<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-08-28 15:51:33
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\slide\bind.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="100px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="单位名称">
            <m-select
              v-model="queryParams.entrustOrganizationId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              clearable
              filterable
              :lists="organizationList"
              lists_label="organizationName"
              lists_value="entrustOrganizationId"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <div class="operation">
        <el-button
          class="register"
          type="primary"
          size="mini"
          @click="openDialog()"
          >登记</el-button
        >
      </div>

      <el-table
        v-loading="loading"
        :data="dataList"
        @row-dblclick="(row) => openDialog(row, '3')"
      >
        <el-table-column
          label="单位名称"
          align="center"
          prop="entrustOrganizationName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="应收样剂量计"
          align="center"
          prop="shouldBindingCount"
          width="150px"
        />
        <el-table-column
          label="已收样剂量计"
          align="center"
          prop="bindingCount"
          width="150px"
        />
        <!-- <el-table-column label="单号/接样日期" align="center" prop="trackingNumber" width="300px" >
        <template slot-scope="{ row }">
          <div v-for="(item, index) in row.otherDataList" :key="index">
            {{ item.trackingNumber }}({{ parseTime(item.samplingDate, "{y}-{m}-{d}") }})
          </div>
        </template>
      </el-table-column> -->
        <el-table-column
          label="接样日期"
          align="center"
          prop="trackingNumber"
          width="300px"
        >
          <template slot-scope="{ row }">
            <div v-for="(item, index) in row.otherDataList" :key="index">
              {{ parseTime(item.samplingDate, "{y}-{m}-{d}") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="监测起始时间"
          align="center"
          prop="wearingBeginTime"
          width="150px"
        >
          <template slot-scope="{ row }">
            {{ parseTime(row.wearingBeginTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="监测结束时间"
          align="center"
          prop="wearingEndTime"
          width="150px"
        >
          <template slot-scope="{ row }">
            {{ parseTime(row.wearingEndTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="要求完成日期"
          align="center"
          prop="requireCompletionDate"
          width="150px"
        >
          <template slot-scope="{ row }">
            {{ parseTime(row.requireCompletionDate, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100px">
          <template slot-scope="{ row }">
            <el-button @click.native.prevent="openDialog(row, '2')" type="text">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 绑定弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :title="title"
      class="bind-dialog"
      @closed="closeDialog"
      v-dialogDrag="true"
    >
      <div class="container">
        <div class="left-container">
          <div class="left-title">
            <span>应检人员</span>
            <div class="">
              <span style="size: 16px">单位：</span>
              <el-select
                v-model="queryParams.companyId"
                filterable
                size="mini"
                placeholder="输入文字检索查询"
                style="width: 250px"
                @change="handleChangeCompanyIng"
              >
                <el-option
                  v-for="item in bindingListing"
                  :key="item.taskPersonalDosimeterId"
                  :label="item.label"
                  :value="item.taskPersonalDosimeterId"
                >
                </el-option>
              </el-select>
              <span style="margin-left: 8px">{{
                inspectPersonList.length
              }}</span>
            </div>
          </div>
          <div>
            <el-input
              v-model="filterNameKeyword"
              placeholder="请输入姓名"
              clearable
            ></el-input>
          </div>
          <!--  -->
          <!-- <el-form
            v-if="status == '1'"
            :model="queryParams"
            ref="queryParams"
            size="small"
            label-width="100px"
          >
            <el-row type="flex" justify="end">
              <el-col :span="12">
                <el-form-item label="单位">
                  <el-select
                    v-model="queryParams.companyId"
                    filterable
                    placeholder="输入文字检索查询"
                    @change="handleChangeCompanyIng"
                  >
                    <el-option
                      v-for="item in bindingListing"
                      :key="item.taskPersonalDosimeterId"
                      :label="item.label"
                      :value="item.taskPersonalDosimeterId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form> -->
          <el-table
            style="width: 100%"
            height="400px"
            :data="filterInspectPersonList"
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              align="center"
              :selectable="selectable"
              width="45px"
              v-if="status != '3'"
            ></el-table-column>
            <el-table-column
              prop="entrustOrganizationName"
              label="单位名称"
              align="center"
              min-width="120"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="dosageNumber"
              label="剂量计编号"
              align="center"
              min-width="140"
            ></el-table-column>
            <el-table-column
              prop="personnelName"
              label="姓名"
              align="center"
              min-width="70"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.personnelName }}</span>
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 1"
                  >(内)</span
                >
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 2"
                  >(外)</span
                >
              </template>
            </el-table-column>
            <el-table-column align="center" width="40" class-name="nopadding">
              <template slot-scope="{ row }">
                <i
                  class="el-icon-right"
                  style="color: #2a72ee; cursor: pointer"
                  v-if="status != '3' && !row.exceptional"
                  @click="handleAddRegister(row)"
                ></i>
              </template>
            </el-table-column>
          </el-table>
          <div class="abnormal">
            <el-button
              type="primary"
              :disabled="selected.length == 0"
              v-if="status != '3'"
              @click="handleException"
              >异常报备</el-button
            >
            <el-button
              type="danger"
              :disabled="selected.length == 0"
              v-if="status != '3'"
              @click="handleDelPeople"
              >删除人员</el-button
            >
          </div>
        </div>

        <div class="right-container">
          <div class="title-container">
            <div class="right-title" :class="status == '3' && 'isView'">
              收样登记
            </div>
            <!-- <el-form inline @submit.native.prevent v-if="status != '3'">
              <el-form-item label="快递单号" label-width="90px">
                <el-input
                  v-model="trackingNumber"
                  placeholder="请输入"
                  clearable
                  size="mini"
									ref="trackingNumber"
                  @keyup.enter.native="submitTracking"
                >
                </el-input>
              </el-form-item>
            </el-form> -->
          </div>

          <el-table :data="trackingList" height="400px">
            <el-table-column
              prop="dosageNumber"
              label="剂量计编号"
              align="center"
              min-width="180"
            >
              <template slot-scope="scope">
                <el-input
                  :disabled="
                    scope.row.state != null &&
                    scope.row.state != '0' &&
                    scope.row.state != '-1' &&
                    scope.row.state != '3' &&
                    !scope.row.exceptional
                  "
                  :ref="'dosageRef_' + scope.$index"
                  v-model="scope.row.dosageNumber"
                  clearable
                  size="mini"
                  @change="changedosageNumber($event, scope.row)"
                  @keyup.enter.native="getPersonList(scope.row, scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="slidesNumber"
              label="剂量元件码"
              align="center"
              min-width="180"
            >
              <template slot="header">
                <span>剂量元件码</span>
                <span @click="handleCopySlidesNumber">
                  <i
                    class="el-icon-copy-document"
                    style="color: #2a72ee; cursor: pointer"
                  ></i>
                </span>
              </template>
              <template slot-scope="scope">
                <el-input
                  :disabled="
                    scope.row.state != null &&
                    scope.row.state != '0' &&
                    scope.row.state != '-1' &&
                    scope.row.state != '3' &&
                    !scope.row.exceptional
                  "
                  :ref="'slidesRef_' + scope.$index"
                  v-model="scope.row.slidesNumber"
                  clearable
                  size="mini"
                  @keyup.enter.native="
                    submitSlideNumber(scope.row, scope.$index)
                  "
                ></el-input>
              </template>
            </el-table-column>
            <!-- <el-table-column
							align="center"
							prop="trackingNumber"
							label="快递单号"
						></el-table-column> -->
            <el-table-column
              align="center"
              prop="entrustOrganizationName"
              :show-overflow-tooltip="true"
              label="单位名称"
              min-width="200"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="personnelName"
              label="姓名"
              min-width="90px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.personnelName }}</span>
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 1"
                  >(内)</span
                >
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 2"
                  >(外)</span
                >
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="监测起止时间"
              align="center"
              min-width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.wearingBeginTime }} -
                {{ scope.row.wearingEndTime }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="60px"
              v-if="status != '3'"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  :disabled="scope.row.state == null"
                  :style="`color: ${
                    scope.row.state == null ? '#f32d2d75' : '#f32d2d'
                  }`"
                  @click="deleteItem(scope.$index)"
                  >解绑</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button style="margin: 10px auto 0" @click="dialogVisible = false"
            >关 闭</el-button
          >
        </div>
      </div>
    </el-dialog>
    <!-- 不同批次弹窗提示显示 -->
    <el-dialog
      :visible.sync="tipsDialogVisible"
      :close-on-click-modal="false"
      :title="tipsTitle"
      width="60%"
      v-dialogDrag="true"
      append-to-body
    >
      <el-form
        class="saveAddPersonInfo"
        :disabled="true"
        :model="saveAddPersonInfo"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单位名称">
              <el-input v-model="saveAddPersonInfo.organizationName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input
                v-model="saveAddPersonInfo.contactsName"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input
                v-model="saveAddPersonInfo.contactsMobile"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="单位地址">
              <el-input
                v-model="saveAddPersonInfo.addressDetails"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="saveAddPersonList" style="width: 100%">
        <el-table-column
          prop="entrustOrganizationName"
          label="单位名称"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="dosageNumber"
          label="剂量计编号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="year"
          label="年份"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="batchNum"
          label="批次"
          align="center"
        ></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="tipsDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 异常报备 -->
    <el-dialog
      :visible.sync="abnormalVisible"
      :close-on-click-modal="false"
      :title="abnormalTitle"
      width="500px"
      v-dialogDrag="true"
      append-to-body
    >
      <el-form
        class="abnormalVisible"
        :model="abnormalFrom"
        size="small"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="异常原因">
              <el-autocomplete
                class="inline-input"
                style="width: 100%"
                v-model="abnormalFrom.describe"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                value-key="label"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="handleAbnormalConfim"
          >确 认</el-button
        >
        <el-button @click="abnormalVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { slidesSampleUpdateState } from "@/api/slides/slideSample";
import {
  entrustOrganizationListing,
  entrustOrganizationList,
  entrustOrganizationDetail,
} from "@/api/person/entrustOrganization";
import { removePersonalResult } from "@/api/slides/task";
import {
  bindingList,
  bindingListing,
  listByDosageNumber,
  bindingAdd,
  getSlideBindingInfo,
  addExceptionalRecord,
  bindingRemove,
} from "@/api/slides/bind";
import MSelect from "@/components/mSelect";

export default {
  name: "bind",
  dicts: ["is_or_no", "exception_type"],
  components: {
    MSelect,
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      status: null,
      list: [],
      // 总列表
      dataList: [],
      rulesseason: {
        season: [
          { required: true, message: "批次不能为空", trigger: "change" },
        ],
      },
      // 表单参数
      form: {},
      // 剂量计
      dosimeter: 0,
      loading: false,
      title: null,
      // 快递单号
      trackingNumber: null,
      // 应检人员列表
      inspectPersonList: [],
      // 视图高度
      height: document.documentElement.clientHeight,
      // 单位下拉框
      organizationList: [],
      // 所有单位下拉
      bindingListing: [],
      trackingList: [],
      // 批次
      seasonList: [],
      formseason: {
        season: [],
      },
      seasonData: {},
      seasoninspectPersonList: [],
      row_index: null,
      visibleseason: false,
      selected: [],
      selecteditem: null,

      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
      saveAddPersonInfo: {},
      saveAddPersonList: [],
      tipsDialogVisible: false,
      tipsTitle: "",
      // 异常
      abnormalTitle: "",
      abnormalVisible: false,
      abnormalFrom: {},
      // 当前对应数据
      useRow: {},
      dosageNumberList: [],
      filterNameKeyword: "",
    };
  },
  computed: {
    filterInspectPersonList() {
      if (!this.inspectPersonList) return [];
      return this.inspectPersonList.filter(
        (item) => item.personnelName.indexOf(this.filterNameKeyword) > -1
      );
    },
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取总列表
    getList() {
      this.loading = true;
      const queryParams = { ...this.queryParams };
      delete bindingList(queryParams)
        .then((response) => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.organizationList.push(...response.rows);
        } else {
          this.organizationList = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    handleAddRegister(row) {
      const newRow = {
        dosageNumber: row.dosageNumber,
        trackingNumber: this.trackingNumber || "",
      };
      const newRowIndex = this.trackingList.findIndex((i) => !i.dosageNumber);
      if (newRowIndex < 0) {
        this.trackingList.push(newRow);
      } else {
        this.$set(this.trackingList, newRowIndex, newRow);
        // this.trackingList[newRowIndex] = newRow
      }
      console.log(
        newRow,
        newRowIndex,
        this.trackingList,
        this.trackingList.length - 1
      );
      this.getPersonList(
        newRow,
        newRowIndex > 0 ? newRowIndex : this.trackingList.length - 1
      );
      // 有空则定到空处 没有则新增一行
      this.getFocus(0, true);
    },
    // 更新状态
    updateState(row, state) {
      slidesSampleUpdateState({
        registrationSlidesSampleId: row.registrationSlidesSampleId,
        state: state,
      }).then((response) => {
        this.getList();
      });
    },
    async getBindingListing() {
      let { code, data } = await bindingListing();
      this.bindingListing = data.reduce((pre, cur) => {
        pre.push({
          ...cur,
          label: `${cur.organizationName}(${cur.year})(${cur.batchNum})`,
        });
        return pre;
      }, []);
      console.log(data);
    },
    handleChangeCompanyIng(val) {
      console.log(val);
      if (!val) {
        this.inspectPersonList = [];
        this.trackingList = [];
      } else {
        this.openDialog(
          {
            taskPersonalDosimeterId: val,
            status: "2",
          },
          null,
          true
        );
      }
    },
    // 打开对话框
    async openDialog(row, status, isAddRow = false) {
      if (row) {
        const response = await getSlideBindingInfo(row.taskPersonalDosimeterId);
        // 左侧
        this.inspectPersonList = response.data.filter((item) => {
          return (
            item.state == "0" ||
            item.state == "-1" ||
            item.state == "3" ||
            item.exceptional
          );
        });
        this.inspectPersonList.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });
        // 右侧
        this.trackingList = response.data.filter((item) => {
          return (
            item.state != "0" &&
            item.state != "-1" &&
            item.state != "3" &&
            !item.exceptional
          );
        });
        this.trackingList.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });
        if (status == "2") {
          this.status = "2";
          this.title = "修改收样登记";
        }
        if (status == "3") {
          this.status = "3";
          this.title = "查看收样登记";
        }
        this.useRow = row;
      } else {
        this.status = "1";
        this.title = "收样登记";
        this.getBindingListing();
      }
      this.dialogVisible = true;
      if (isAddRow) this.submitTracking();
      if (!row) {
        this.$nextTick(() => {
          this.$refs[`trackingNumber`]?.focus();
        });
      }
    },
    // 提交剂量计编号
    async getPersonList(row, index, inspectPersonList) {
      if (!row.dosageNumber || row.dosageNumber.trim() === "") {
        this.$modal.msgWarning("剂量计编号不能为空");
        return false;
      }
      let isRepeat = false;

      let shortindex = row.dosageNumber.indexOf("-");
      const arr = this.trackingList.filter((item, ind) => {
        console.log(item, ind);
        if (row.dosageNumber === item.slidesNumber) {
          /* 剂量计编号与滑片码重复 */
          isRepeat = true;
        }
        if (shortindex != "-1") {
          return (
            ind != index &&
            row.dosageNumber == item.dosageNumber + "-" + item.batchNum
          ); /* 剂量计编号与剂量计编号重复 */
        } else {
          return (
            ind != index && row.dosageNumber == item.dosageNumber
          ); /* 剂量计编号与剂量计编号重复 */
        }
      });
      if (isRepeat) {
        this.$modal.msgWarning(
          `剂量计编号：${row.dosageNumber}与剂量元件码重复`
        );
        this.$set(row, "dosageNumber", "");
        this.$refs[`dosageRef_${index}`]?.focus();
        return;
      }
      if (arr.length >= 1) {
        if (shortindex != "-1") {
          let dosageleft = row.dosageNumber.slice(0, shortindex);
          this.$modal.msgWarning(`剂量计编号：${dosageleft}已存在`);
        } else {
          this.$modal.msgWarning(`剂量计编号：${row.dosageNumber}已存在`);
        }
        this.$set(row, "dosageNumber", "");
        this.$refs[`dosageRef_${index}`]?.focus();
        return;
      }
      if (row.dosageNumber.trim() !== "") {
        this.listPersonList(row, index);
      }
    },
    // 请求人员数据
    listPersonList(row, row_index) {
      let shortindex = row.dosageNumber.indexOf("-");
      let dosageleft = "";
      let dosageright = "";
      if (shortindex != "-1") {
        dosageleft = row.dosageNumber.slice(0, shortindex);
        dosageright = row.dosageNumber.slice(shortindex + 1);
      } else {
        dosageleft = row.dosageNumber;
        dosageright = "";
      }
      this.$set(row, "dosageNumber", dosageleft);
      this.$set(row, "dosageright", dosageright);

      const index = this.inspectPersonList.findIndex(
        (item) => item.dosageNumber === dosageleft
      );
      if (index > -1) {
        /* 左侧有 */
        const obj = this.inspectPersonList[index];
        for (const key in obj) {
          this.$set(row, key, obj[key]);
        }
        this.inspectPersonList.splice(index, 1);
        // this.getFocus();
        // return;
      }
      // if (row.dosageNumber == row.defaultDosageNumber) { /* 键入相同值 不请求 */
      //   return;
      // }
      let querydosage = row.dosageright
        ? row.dosageNumber + "-" + row.dosageright
        : row.dosageNumber;
      listByDosageNumber(querydosage)
        .then(async (response) => {
          if (response.data.length === 0) {
            row.dosageNumber = "";
            this.$modal.msgWarning("没有查到应检人员,请重新输入");
            this.$refs["dosageRef_" + row_index]?.focus();
            return;
          } else {
            response.data.forEach((item) => {
              item.defaultDosageNumber = item.dosageNumber;
            });
            this.row_index = row_index;
            // 判断是否为同一单位， 同一年份，同一批次
            const isBoolean = await this.judgeTips(row);
            if (isBoolean >= 0) {
              let { data } = await entrustOrganizationDetail(
                response.data[0].entrustOrganizationId
              );
              this.saveAddPersonInfo = data;
              // 单位  联系人 电话  地址
              // this.tipsTitle = `${data.organizationName} ${data.dosageContactsName} ${data.dosageContactsMobile} ${data.addressDetails}`
              this.tipsTitle = `查看详情`;
              this.saveAddPersonList = [...response.data];
              this.dosageNumberList.push({
                personnelId: row.personnelId,
                dosageNumber: row.dosageNumber,
              });
              this.$set(this.trackingList[row_index], "dosageNumber", "");
              this.$refs["dosageRef_" + row_index]?.focus();
              return;
            }

            await this.pushdata(response.data);
            // 第二行开始 或者 做了标记的行
            if (row_index > 0 || row.mark)
              this.submitSlideNumber(row, row_index);
          }
        })
        .catch((response) => {
          row.dosageNumber = "";
          this.$refs["dosageRef_" + row_index]?.focus();
        });
    },
    // 检测本检测周期的个人剂量计提示
    async judgeTips(row) {
      const isTips = [...this.trackingList].findIndex((i) => {
        if (!i.dosageNumber) {
          // 判断是空 则默认为假  不展示提示
          return false;
        }
        return (
          i.entrustOrganizationId != row.entrustOrganizationId ||
          i.year != row.year ||
          i.batchNum != row.batchNum
        );
      });
      if (isTips >= 0) {
        console.log(this.saveAddPersonList);
        this.tipsDialogVisible = true;
        this.$modal.msgWarning(`不是本检测周期的个人剂量计`);
      }
      return isTips;
    },
    // 将获取的数据推入左右两侧
    async pushdata(list) {
      // 从获取的列表中寻找当前键入人员
      let row = this.trackingList[this.row_index];
      const obj = list.find((item) => {
        return item.dosageNumber === row.dosageNumber;
      });
      if (obj) {
        if (obj.state == "3" || obj.exceptional) {
          /* state为3或exceptional为true 移入左边 */
          this.inspectPersonList.push(obj);
          for (const key in row) {
            this.$set(row, key, null);
          }
        } else {
          for (const key in obj) {
            this.$set(row, key, obj[key]);
          }
          // 已经出结果的用本身的快递单号 否则用新输入的
          if (!obj.state || (obj.state == "0" && obj.state == "-1")) {
            this.$set(row, "trackingNumber", this.trackingNumber);
          }
        }
      }

      // 过滤
      this.$nextTick(() => {
        // 推入左侧
        let lList = list.filter((item) => {
          return (
            item.dosageNumber != row.dosageNumber &&
            (item.state == "0" ||
              item.state == "-1" ||
              item.state == "3" ||
              item.exceptional)
          );
        });
        let lListFilt = lList.filter((item) => {
          return !this.inspectPersonList.find(
            (it) =>
              item.dosageNumber == it.dosageNumber &&
              item.batchNum === it.batchNum
          );
        });
        lListFilt.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });

        // 首次调用接口可以插入左侧   后续调用均不插入且保存数据方便dialog弹窗展示
        if (this.inspectPersonList.length == 0) {
          this.inspectPersonList.push(...lListFilt);
        } else {
          this.saveAddPersonList = [...list];
          console.log(this.saveAddPersonList);
        }

        // 推入右侧
        let rList = list.filter((item) => {
          return (
            item.dosageNumber != row.dosageNumber &&
            item.state != "0" &&
            item.state != "-1" &&
            item.state != "3" &&
            !item.exceptional
          );
        });
        let rListFilt = rList.filter((item) => {
          return !this.trackingList.find((it) => {
            return (
              item.dosageNumber == it.dosageNumber &&
              item.batchNum == it.batchNum
            );
          });
        });
        rListFilt.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });
        if (this.trackingList.length == 0) {
          this.trackingList.unshift(...rListFilt);
          this.getFocus();
        }
      });
    },
    // 键入不同值 清空信息 （正确值会清空并重赋信息）
    changedosageNumber(val, row) {
      if (row.personnelName && val != row.defaultDosageNumber) {
        /* 键入不同值 还原  */
        let obj = { ...row };
        obj.dosageNumber = row.defaultDosageNumber;
        this.inspectPersonList.push(obj);
        console.log("键入不同值", obj);
        this.$set(row, "entrustOrganizationId", null);
        this.$set(row, "entrustOrganizationName", null);
        this.$set(row, "personnelId", null);
        this.$set(row, "personnelName", null);
        this.$set(row, "taskPersonalResultId", null);
        this.$set(row, "wearingBeginTime", null);
        this.$set(row, "wearingEndTime", null);
        this.$set(row, "slidesNumber", null);
        this.$set(row, "batchNum", null);
        this.$set(row, "dosageright", null);
        this.$set(row, "exceptional", null);
      }
    },
    // 绑定
    submitSlideNumber(row, index) {
      if (typeof index === "number" && !isNaN(index)) {
        if (!row.dosageNumber || row.dosageNumber.trim() === "") {
          this.$modal.msgWarning("请先输入剂量计编号");
          this.$set(row, "slidesNumber", "");
          this.$refs[`dosageRef_${index}`]?.focus();
          return false;
        }
        // 第一行才需要
        if (index == 0 && !row.mark) {
          if (!row.slidesNumber || row.slidesNumber.trim() === "") {
            this.$modal.msgWarning("剂量元件码不能为空");
            return false;
          }
        }
        let isRepeat = false;
        const arr = this.trackingList.filter((item) => {
          if (
            row.slidesNumber == item.dosageNumber + "-" + item.batchNum ||
            row.slidesNumber == item.dosageNumber
          ) {
            isRepeat = true;
          }
          return item.slidesNumber === row.slidesNumber;
        });
        const slidesNumber = row.slidesNumber;
        if (isRepeat) {
          this.$modal.msgWarning(`剂量元件码：${slidesNumber}与剂量计编号重复`);
          this.$set(row, "slidesNumber", "");
          this.$refs[`slidesRef_${index}`]?.focus();
          return;
        } else if (arr.length > 1 && !isRepeat) {
          this.$modal.msgWarning(`剂量元件码：${slidesNumber}已存在`);
          this.$set(row, "slidesNumber", "");
          this.$refs[`slidesRef_${index}`]?.focus();
          return;
        }
        if (!row.slidesNumber || row.slidesNumber.trim() !== "") {
          /* 开始绑定 */
          bindingAdd(row).then((response) => {
            row.slidesNumber = response.data.slidesNumber || "";
            row.state = 1;
            this.$modal.msgSuccess("收样成功");
            this.getFocus(index);
          });
        }
      }
    },
    // 提交快递单号
    submitTracking() {
      // if (!this.trackingNumber || this.trackingNumber.trim() === "") {
      // 	return this.$modal.msgWarning("快递单号不能为空");
      // }
      if (this.trackingList.length == 0) {
        this.trackingList.push({
          mark: true,
          trackingNumber: this.trackingNumber || "",
        });
      }
      // 有空则定到空处 没有则新增一行
      this.getFocus(0, true);
    },
    // 光标定位(从index行开始向下搜寻为空且没有禁用的格子，找到则聚焦，没有则搜寻下一行，到最后一行还没找到，则新增一行)
    getFocus(index = 0, mark = false) {
      this.$nextTick(() => {
        const value = this.$refs[`dosageRef_${index}`]?.value;
        const slidesValue = this.$refs[`slidesRef_${index}`]?.value;
        if (
          (!value || value.trim() === "") &&
          !this.$refs[`dosageRef_${index}`]?.disabled
        ) {
          this.$refs[`dosageRef_${index}`]?.focus();
          if (this.trackingList[index]) {
            this.trackingList[index].mark = mark;
            this.trackingList[index].trackingNumber = this.trackingNumber;
          }
          return false;
        } else if (
          (!slidesValue || slidesValue.trim() === "") &&
          !this.$refs[`slidesRef_${index}`]?.disabled
        ) {
          this.$refs[`slidesRef_${index}`]?.focus();
          if (this.trackingList[index]) {
            this.trackingList[index].mark = mark;
            this.trackingList[index].trackingNumber = this.trackingNumber;
          }
          return false;
        }
        // 当index等于绑定登记列表的下标值时 则新增一条
        if (index === this.trackingList.length - 1) {
          this.trackingList.push({
            mark: mark,
            trackingNumber: this.trackingNumber,
          });
        }
        this.getFocus(index + 1, mark);
      });
    },
    // 解绑
    deleteItem(index) {
      const state = this.trackingList[index].state;
      if (state == -1 || state == 0) {
        this.trackingList[index].state = 0;
        this.trackingList[index].slidesNumber = null;
        if (!this.trackingList[index].dosageNumber) {
          const findIndex = this.dosageNumberList.findIndex(
            (it) => it.personnelId == this.trackingList[index].personnelId
          );
          if (findIndex > -1) {
            this.trackingList[index].dosageNumber =
              this.dosageNumberList[findIndex].dosageNumber;
            this.dosageNumberList.splice(findIndex, 1);
          }
        }
        this.inspectPersonList.push(this.trackingList[index]);
        this.trackingList.splice(index, 1);
        this.$modal.msgSuccess("解绑成功");
        this.getFocus(index);
        return;
      }
      this.$modal.confirm(`确定解绑该剂量计吗？`).then(() => {
        bindingRemove(this.trackingList[index].taskPersonalResultId).then(
          (response) => {
            this.trackingList[index].state = 0;
            this.trackingList[index].slidesNumber = null;
            if (!this.trackingList[index].dosageNumber) {
              const findIndex = this.dosageNumberList.findIndex(
                (it) => it.personnelId == this.trackingList[index].personnelId
              );
              if (findIndex > -1) {
                this.trackingList[index].dosageNumber =
                  this.dosageNumberList[findIndex].dosageNumber;
                this.dosageNumberList.splice(findIndex, 1);
              }
            }
            this.inspectPersonList.push(this.trackingList[index]);
            this.trackingList.splice(index, 1);
            this.$modal.msgSuccess("解绑成功");
            this.getFocus(index);
          }
        );
      });
    },
    // 更改勾选
    handleSelectionChange(selection) {
      this.selected = selection;
    },
    // 异常报备
    handleException() {
      let ids = this.selected.map((item) => {
        if (item.taskPersonalResultId) {
          return item.taskPersonalResultId;
        }
      });
      this.abnormalTitle = "确定异常报备吗？";
      this.abnormalFrom = {
        taskPersonalResultId: ids,
        exceptionType: 1,
      };
      this.abnormalVisible = true;
      // let ids = this.selected.map(item => {
      // 	if(item.taskPersonalResultId) {
      // 		return item.taskPersonalResultId
      // 	}
      // })
      // this.$modal.confirm(`确定异常报备吗？`).then(() => {
      // 	addExceptionalRecord({
      // 		taskPersonalResultId: ids,
      // 		exceptionType: 1
      // 	}).then((response) => {
      // 		this.$modal.msgSuccess("报备成功");
      // 		this.selected.forEach(item => {
      // 			item.exceptional = true;
      // 		});
      // 	});
      // });
    },
    handleDelPeople() {
      let ids = this.selected.map((item) => {
        if (item.taskPersonalResultId) {
          return item.taskPersonalResultId;
        }
      });
      this.$confirm("是否删除应检人员", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removePersonalResult({
            taskPersonalDosimeterId: this.useRow.taskPersonalDosimeterId,
            taskPersonalResultIds: ids,
          }).then((res) => {
            ids.forEach((item) => {
              let index = this.inspectPersonList.findIndex(
                (i) => i.taskPersonalResultId == item
              );
              index > -1 && this.inspectPersonList.splice(index, 1);
            });
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {});
    },
    handleAbnormalConfim() {
      addExceptionalRecord(this.abnormalFrom).then((response) => {
        this.$modal.msgSuccess("报备成功");
        this.selected.forEach((item) => {
          item.exceptional = true;
        });
        this.abnormalVisible = false;
      });
    },
    querySearch(queryString, cb) {
      let restaurants = this.dict.type.exception_type;
      let results = queryString
        ? restaurants.filter((i) => i.label.indexOf(queryString) > -1)
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // 关闭弹框
    closeDialog() {
      this.trackingNumber = null;
      this.dosimeter = 0;
      this.trackingList = [];
      this.inspectPersonList = [];
      this.dialogVisible = false;
      this.queryParams.companyId = "";
      this.getList();
    },
    // 列表标红
    tableRowClassName({ row, rowIndex }) {
      if (row.exceptional) {
        return "warning-row";
      }
      return "";
    },
    // 已报备的不允许勾选
    selectable(row, rowIndex) {
      if (row.exceptional) {
        return false;
      } else {
        return true;
      }
    },
    // 复制剂量元件码
    handleCopySlidesNumber() {
      let text = this.trackingList
        .filter((item) => !!item.slidesNumber)
        .map((item) => item.slidesNumber)
        .join("\n");
      this.$copyText(text);
      this.$modal.msgSuccess("复制成功");
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}

::v-deep.el-table {
  .nopadding {
    .cell {
      padding: 0;
    }
  }
}
.bind-dialog {
  ::v-deep.el-dialog {
    background: transparent;
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      padding: 0 0;
      max-height: unset !important;
      .el-table--medium .el-table__cell {
        padding: 4px 0;
      }
    }
  }
}
.container {
  display: flex;

  .left-container {
    width: 35%;
    border-radius: 10px;
    background: #fff;
    padding: 10px 15px;
    display: flex;
    flex-direction: column;
    .left-title {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      > span {
        &:first-child {
          position: relative;
          color: #252d57;
          font-weight: bold;
          padding-left: 15px;
          font-size: 18px;
          &::before {
            content: "";
            width: 5px;
            height: 100%;
            background-color: #2a72ee;
            border-radius: 5px;
            position: absolute;
            left: 0;
            bottom: 0;
          }
        }
      }
    }
    .abnormal {
      width: fit-content;
      margin: 10px auto 0 auto;
    }
  }
  .right-container {
    margin-left: 10px;
    width: calc(65% - 10px);
    background: #fff;
    border-radius: 10px;
    text-align: center;
    padding: 10px 15px;
    display: flex;
    flex-direction: column;
    .title-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .right-title {
        position: relative;
        color: #252d57;
        font-weight: bold;
        padding-left: 15px;
        font-size: 18px;
        &::before {
          content: "";
          width: 5px;
          height: 100%;
          background-color: #2a72ee;
          border-radius: 5px;
          position: absolute;
          left: 0;
          bottom: 0;
        }
      }
      ::v-deep.el-form-item {
        margin-bottom: 3px;
      }
    }
    .el-table {
      margin-top: 15px;
      flex: 1;
    }
    .closedialog {
      width: fit-content;
      margin: auto auto 0 auto;
    }
  }
  .row-hei {
    width: 100%;
    height: 90%;
  }
}

.operation {
  margin-bottom: 20px;
  .register {
    padding-inline: 30px;
  }
}
.uploadbutton {
  padding-inline: 20px;
}
.myupload {
  margin-bottom: 20px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
::v-deep .el-table .warning-row {
  color: red;
}
.searchcontainer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  margin-top: -10px;
}
.viewform {
  justify-content: flex-end;
}
.seasondialog .el-dialog__body .el-form {
  width: fit-content;
  margin: 0 auto;
}
::v-deep .bind-dialog.el-dialog__wrapper {
  top: 10px;
  right: 10px;
  bottom: 10px;
  left: 10px;
  .el-dialog {
    width: 100%;
    height: 100%;
    margin-top: 0 !important;
    max-height: 100%;
    .el-dialog__body {
      height: 100%;
      .container {
        height: 100%;
      }
    }
  }
}
.seasonitem {
  display: flex;
  align-items: center;
  width: fit-content;
  margin-left: 130px;
  margin-bottom: 10px;
  .el-button {
    margin-left: 20px;
  }
}
.seasondialog {
  ::v-deep .el-dialog__body {
    padding-bottom: 10px;
  }
}
.isView {
  margin-bottom: 7px;
  margin-top: 10px;
}


</style>
